#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
验证 View Specifications 按钮定位逻辑
专门测试每个车型的 View Specifications 按钮是否能被正确找到
"""

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.action_chains import ActionChains

class ViewSpecificationsVerifier:
    """View Specifications 按钮验证器"""
    
    def __init__(self):
        self.setup_driver()
        
    def setup_driver(self):
        """设置Chrome WebDriver"""
        chrome_options = Options()
        chrome_options.add_argument('--disable-blink-features=AutomationControlled')
        chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
        chrome_options.add_experimental_option('useAutomationExtension', False)
        chrome_options.add_argument('--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15')
        
        service = Service(ChromeDriverManager().install())
        self.driver = webdriver.Chrome(service=service, options=chrome_options)
        self.wait = WebDriverWait(self.driver, 10)
        self.actions = ActionChains(self.driver)
    
    def verify_view_specifications_buttons(self):
        """验证所有车型的 View Specifications 按钮"""
        try:
            print("🔍 开始验证 View Specifications 按钮")
            print("="*60)
            
            # 访问页面
            url = "https://www.ford.co.uk/shop/build-your-ford/ngc2/ice2/model?catalogId=WAEGB-CGE-2022-FocusMCAGBR202450&series=ACMAA_VS-DH&planId=c"
            print(f"📖 访问页面: {url}")
            self.driver.get(url)
            time.sleep(5)
            
            # 处理Cookie
            self.handle_cookies()
            
            # 等待页面加载
            print(f"\n⏳ 等待车型元素加载...")
            time.sleep(5)
            
            # 获取所有车型
            car_elements = self.driver.find_elements(By.CSS_SELECTOR, 'div[data-cy][class*="ProductTile"]')
            print(f"🚗 找到 {len(car_elements)} 个车型元素")
            
            results = {}
            
            for i, car_element in enumerate(car_elements, 1):
                car_name = car_element.get_attribute('data-cy')
                print(f"\n🔍 第 {i} 个车型: {car_name}")
                
                # 检查车型可见性
                is_displayed = car_element.is_displayed()
                print(f"   可见性: {'可见' if is_displayed else '隐藏'}")
                
                if is_displayed:
                    # 方法1: 直接在车型元素内查找
                    view_spec_button = self.find_view_spec_button_method1(car_element, car_name)
                    
                    if not view_spec_button:
                        # 方法2: 鼠标悬停后查找
                        view_spec_button = self.find_view_spec_button_method2(car_element, car_name)
                    
                    if not view_spec_button:
                        # 方法3: 全局查找
                        view_spec_button = self.find_view_spec_button_method3(car_name)
                    
                    results[car_name] = {
                        'visible': is_displayed,
                        'button_found': view_spec_button is not None,
                        'button_element': view_spec_button
                    }
                else:
                    results[car_name] = {
                        'visible': is_displayed,
                        'button_found': False,
                        'button_element': None
                    }
                    print(f"   ❌ 车型隐藏，跳过按钮检查")
            
            # 输出总结
            self.print_summary(results)
            
            return results
            
        except Exception as e:
            print(f"❌ 验证过程出错: {e}")
            return {}
        finally:
            input("按Enter键关闭浏览器...")
            self.driver.quit()
    
    def handle_cookies(self):
        """处理Cookie"""
        try:
            cookie_script = """
                var cookieElements = document.querySelectorAll('[class*="cookie"], [class*="Cookie"], [class*="consent"]');
                cookieElements.forEach(function(el) {
                    el.style.display = 'none';
                });
            """
            self.driver.execute_script(cookie_script)
            print(f"✓ Cookie处理完成")
        except Exception as e:
            print(f"❌ Cookie处理出错: {e}")
    
    def find_view_spec_button_method1(self, car_element, car_name):
        """方法1: 直接在车型元素内查找"""
        try:
            print(f"   📍 方法1: 在车型元素内直接查找...")
            
            # 尝试多种选择器
            selectors = [
                'button[data-cy="product-tile-overlay"]',
                'button.ButtonAsLink-sc-6m73s-0.kMrUGm',
                'button:contains("View Specifications")',
                'button[aria-hidden="false"]',
                '[class*="ButtonAsLink"]'
            ]
            
            for selector in selectors:
                try:
                    if ':contains(' in selector:
                        # 使用JavaScript查找包含文本的按钮
                        buttons = self.driver.execute_script("""
                            var elements = arguments[0].querySelectorAll('button');
                            var result = [];
                            for (var i = 0; i < elements.length; i++) {
                                if (elements[i].textContent.includes('View Specifications')) {
                                    result.push(elements[i]);
                                }
                            }
                            return result;
                        """, car_element)
                        if buttons:
                            print(f"      ✓ 找到按钮 (文本搜索): {len(buttons)} 个")
                            return buttons[0]
                    else:
                        buttons = car_element.find_elements(By.CSS_SELECTOR, selector)
                        if buttons:
                            print(f"      ✓ 找到按钮 (选择器: {selector}): {len(buttons)} 个")
                            for btn in buttons:
                                text = btn.text.strip()
                                if 'View Specifications' in text or text == '':
                                    print(f"      ✓ 按钮文本: '{text}'")
                                    return btn
                except Exception as e:
                    pass
            
            print(f"      ❌ 方法1未找到按钮")
            return None
            
        except Exception as e:
            print(f"      ❌ 方法1出错: {e}")
            return None
    
    def find_view_spec_button_method2(self, car_element, car_name):
        """方法2: 鼠标悬停后查找"""
        try:
            print(f"   📍 方法2: 鼠标悬停后查找...")
            
            # 滚动到元素位置
            self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", car_element)
            time.sleep(1)
            
            # 鼠标悬停
            self.actions.move_to_element(car_element).perform()
            time.sleep(2)
            
            # 再次查找按钮
            selectors = [
                'button[data-cy="product-tile-overlay"]',
                'button.ButtonAsLink-sc-6m73s-0',
                '[class*="ButtonAsLink"]'
            ]
            
            for selector in selectors:
                try:
                    buttons = car_element.find_elements(By.CSS_SELECTOR, selector)
                    if buttons:
                        for btn in buttons:
                            if btn.is_displayed():
                                text = btn.text.strip()
                                print(f"      ✓ 悬停后找到按钮: '{text}' (选择器: {selector})")
                                return btn
                except Exception as e:
                    pass
            
            print(f"      ❌ 方法2未找到按钮")
            return None
            
        except Exception as e:
            print(f"      ❌ 方法2出错: {e}")
            return None
    
    def find_view_spec_button_method3(self, car_name):
        """方法3: 在整个页面中全局查找"""
        try:
            print(f"   📍 方法3: 全局查找...")
            
            # 查找所有可能的按钮
            all_buttons = self.driver.find_elements(By.CSS_SELECTOR, 'button')
            
            for button in all_buttons:
                try:
                    if button.is_displayed():
                        text = button.text.strip()
                        data_cy = button.get_attribute('data-cy')
                        class_name = button.get_attribute('class')
                        
                        if ('View Specifications' in text or 
                            data_cy == 'product-tile-overlay' or
                            (class_name and 'ButtonAsLink' in class_name)):
                            print(f"      ✓ 全局找到按钮:")
                            print(f"        文本: '{text}'")
                            print(f"        data-cy: '{data_cy}'")
                            print(f"        class: '{class_name}'")
                            return button
                except Exception as e:
                    pass
            
            print(f"      ❌ 方法3未找到按钮")
            return None
            
        except Exception as e:
            print(f"      ❌ 方法3出错: {e}")
            return None
    
    def print_summary(self, results):
        """打印总结"""
        try:
            print(f"\n📊 View Specifications 按钮验证总结:")
            print(f"="*60)
            
            total_cars = len(results)
            visible_cars = len([r for r in results.values() if r['visible']])
            found_buttons = len([r for r in results.values() if r['button_found']])
            
            print(f"总车型数: {total_cars}")
            print(f"可见车型: {visible_cars}")
            print(f"找到按钮: {found_buttons}")
            print(f"成功率: {found_buttons}/{visible_cars} = {found_buttons/visible_cars*100:.1f}%" if visible_cars > 0 else "成功率: 0%")
            
            print(f"\n📝 详细结果:")
            for car_name, result in results.items():
                status = "✅" if result['button_found'] else "❌"
                visibility = "可见" if result['visible'] else "隐藏"
                print(f"  {status} {car_name}: {visibility}, 按钮: {'找到' if result['button_found'] else '未找到'}")
            
            # 找到按钮的车型，测试点击
            if found_buttons > 0:
                print(f"\n🖱️  测试按钮点击功能:")
                for car_name, result in results.items():
                    if result['button_found'] and result['button_element']:
                        print(f"  🔍 测试 {car_name} 的按钮...")
                        try:
                            button = result['button_element']
                            # 滚动到按钮
                            self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button)
                            time.sleep(1)
                            
                            # 点击按钮
                            button.click()
                            time.sleep(2)
                            
                            # 检查是否有反应（比如URL变化，弹窗等）
                            current_url = self.driver.current_url
                            print(f"    ✓ 点击成功，当前URL: {current_url}")
                            
                            # 如果点击后有变化，尝试返回
                            if 'model' not in current_url:
                                self.driver.back()
                                time.sleep(2)
                            
                            break  # 只测试第一个找到的按钮
                        except Exception as e:
                            print(f"    ❌ 点击测试失败: {e}")
            
        except Exception as e:
            print(f"❌ 总结打印出错: {e}")

def main():
    """主函数"""
    verifier = ViewSpecificationsVerifier()
    results = verifier.verify_view_specifications_buttons()
    
    print(f"\n🏁 验证完成！")
    if results:
        found_count = len([r for r in results.values() if r['button_found']])
        visible_count = len([r for r in results.values() if r['visible']])
        if found_count == visible_count and visible_count > 0:
            print(f"🎉 所有可见车型的按钮都找到了！")
        else:
            print(f"⚠️  需要优化按钮定位逻辑")

if __name__ == "__main__":
    main()
